package at.fhhgb.mc.android.mfb_hgb.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import at.fhhgb.mc.android.mfb_hgb.R;

public class OverviewActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

	private static final String LOG_TAG = "OverViewActivity";

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_overview);

		mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
	}

	public boolean test = false;

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction ft = fragmentManager.beginTransaction();
		Fragment f = null;

		clearBackstack();
		
		switch (position) {
		case 0:
			f = new FragmentOverview();
			f.setArguments(new Bundle());
			break;

		case 1:
			f = new SearchFragment();
			break;

		case 2:
			f = new FragmentProfile();
			break;
		}

		ft.replace(R.id.container, f);
		ft.commit();
	}

	private void clearBackstack() {
		// Clear all back stack.
		int backStackCount = getFragmentManager().getBackStackEntryCount();
		for (int i = 0; i < backStackCount; i++) {

		    // Get the back stack fragment id.
		    int backStackId = getFragmentManager().getBackStackEntryAt(i).getId();

		    getFragmentManager().popBackStack(backStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE);

		}
	}

	// To use backstack
	@Override
	public void onBackPressed() {
		FragmentManager fm = getFragmentManager();
		if (fm.getBackStackEntryCount() > 0) {
			fm.popBackStack();
		} else {
			super.onBackPressed();
		}
	}
	
	public boolean isDrawerOpened(){
		return mNavigationDrawerFragment.isDrawerOpen();
	}
}